import message
from datetime import datetime
import json
import time
# import logging
import picologging as logging
logging.basicConfig()

data_file = "data.json"

def reload_message_queue_timer(minutes):
    # with open(data_file, 'w') as f:
        # json.dump([message_queue], f)
    def isReloadTime():
        print('minute is ',datetime.now().minute)
        print('minutes is ',minutes)
        if datetime.now().minute % minutes == 0 and datetime.now().second == 0:
            return True
        else:
            return False
    return isReloadTime
def init_logger(name):
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_handler = logging.FileHandler(
        "/root/.logs/app.log", mode="a", encoding="utf-8"
    )
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    # 指定日志记录的格式
    file_handler.setFormatter(formatter)
    # 创建Logger对象，指定日志级别
    global logger
    logger = logging.getLogger(name)
    logger.addHandler(file_handler)

def init_message_queue():
    try:
        with open(data_file, 'r') as file:
            data = json.load(file)
            if data[0] is None:
                raise Exception('Data file is empty or not found')
            else:
                if data[0]['metadata'] is None:
                    print('message queue is empty')
                    current_time = datetime.now().strftime("%H:%M:%S")
                    meta_data = message.Message_metadata(create_time=current_time,update_time=current_time,data_length=0)
                    data = message.Message_queue(metadata=meta_data)
                    return data
                else:
                    if data[0]['metadata']['data_length'] == 0:
                        print('message queue is empty')
                        current_time = datetime.now().strftime("%H:%M:%S")
                        meta_data = message.Message_metadata(create_time=data[0]['metadata']['create_time'],update_time=current_time,data_length=0)
                        data = message.Message_queue(metadata=meta_data)
                        return data
                    else:
                        meta_data = message.Message_metadata(create_time=data[0]['metadata']['create_time'],update_time=data[0]['metadata']['update_time'],data_length=data[0]['metadata']['data_length'])
                        new_data = message.Message_queue(metadata=meta_data)
                        if len(data) > 1:
                            for i in range(1, len(data)):
                                print('data[i] is ',data[i])
                                print('data[i][data] is ',data[i]['data'])
                                print('data[i][time] is ',data[i]['time'])
                                temp_message = message.Message(data=data[i]['data'],time=data[i]['time'])
                                new_data.add_message(temp_message)
                        return new_data
    except json.JSONDecodeError as e:
        print(f"Error decoding JSON: {e}")
    print('message queue is empty')
    current_time = datetime.now().strftime("%H:%M:%S")
    meta_data = message.Message_metadata(create_time=current_time,update_time=current_time,data_length=0)
    data = message.Message_queue(metadata=meta_data)
    return data
def message_queue_enqueue(message_queue, new_message):
    print('message queue enqueue')
    message_queue.add_message(new_message)
    print('after')
def get_last_message(message_queue):
    # last_index = len(message_queue.messages) - 1
    return message_queue.get_message(index=len(message_queue.messages)-1)
def get_messages(message_queue, message_length):
    messages = []
    for index in range(len(message_queue.messages)-message_length, len(message_queue.messages)):
        print('index is ',index)
        print('message_queue.messages is ',message_queue.get_message(index=index))
        messages.append(message_queue.get_message(index=index))
    print('messages is ',messages)
    return messages
    # return message_queue.get_message(index=index)

def write_to_file(filename, data):
    with open(filename, 'w') as file:
        json.dump(data, file)

# init_message_queue()